#Main file to be executed with the comand 'vecti'

require 'app.rb'
require 'tokens/InvalidToken.rb'
require 'lexer.rb'
require 'parser/parser.tab.rb'

# Validating and analizing input arguments
if ARGV[1] == "-e"
  if ARGV[2] == "" || ARGV[3] != ""
    puts ("Error en los argumentos pasados:\n" +
          "Llamada correcta: $vecti archivo.rb\n" +
          "                  $vecti -e \"comandos_vectorinox\" ")
    return
  end
  inp = ARGV[2]
elsif ARGV[1] != "-e" && ARGV[1] != ""
  if ARGV[2] != ""
    puts ("Error en los argumentos pasados:\n" +
          "Llamada correcta: $vecti archivo.rb\n" +
          "                  $vecti -e \"comandos_vectorinox\" ")
    return
  end
  inp = ARGV[1]
  if ("/" != inp[0,1])
    inp = ARGV[0] + "/" + inp
  end
  inp = File.new(inp, "r")
else
  puts("Error en los argumentos pasados:\n" +
          "Llamada correcta: $vecti archivo.rb\n" +
          "                 $vecti -e \"comandos_vectorinox\" ")
  return  
end

for token_class_name in $tokens
  autoload :"#{token_class_name}", "tokens/#{token_class_name}.rb"
end

# Creating lexer
lex = Lexer.new(inp)
lex.tokens = $tokens
#DEBUG puts "The input string is: #{lex.input}"
parse_tk = Array.new()
error = false

#Analizing file
while
  begin
    tk = lex.yylex()
    break if nil == tk
    next if error 
    parse_tk.push([:"#{tk.class.name}", tk])
  rescue InvalidToken => ex0
    puts ("ERROR: Caracter no esperado '#{ex0.char.chr}' en la linea #{ex0.line}, columna #{ex0.column}.\n")
    error = true
  end
end

if !error
  a = Parser.new.parse(parse_tk)
  #puts a.to_s
  msg = a.check
  if nil != msg
    puts msg
  else
    msg = a.run
    if nil != msg
      puts msg
    end
  end
end